//
//  PopoverVC.swift
//  iIHS
//
//  Created by iGhibli on 2021/7/2.
//

import Cocoa

class PopoverVC: NSViewController {

    @IBOutlet weak var dstView: DestinationView!
    @IBOutlet weak var previewImageView: NSImageView!
    @IBOutlet weak var outLabel: NSTextField!
    
    typealias RunScriptResult = (_ runResult: String) -> ()
    
    static let shellScriptFile = "/Users/lindada/Documents/GitHub/IHS/iIHS/iIHS.sh"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        dstView.delegate = self
    }
    
    // MARK: - Actions
    @IBAction func setApp(_ sender: NSButton) {
        
    }
    
    @IBAction func quitApp(_ sender: NSButton) {
        NSApplication.shared.terminate(self)
    }
    
    func runScript(_ path: String?, onComplete: @escaping RunScriptResult) {
        guard let path = path, FileManager.default.fileExists(atPath: path) else {
            onComplete("路径不存在！")
            return
        }
        
        let task = Process()
        task.launchPath = "/bin/sh"
        // 向Shell脚本传参["执行的Shell脚本路径", "上传图片路径", "当前时间戳", "图片描述"]
        task.arguments = [Self.shellScriptFile, path]
        let outPipe = Pipe()
        task.standardOutput = outPipe
        task.launch()
        let fileHandle = outPipe.fileHandleForReading
        let data = fileHandle.readDataToEndOfFile()
        let result = String.init(data: data, encoding: .utf8)
        task.waitUntilExit()
        // 获取运行结果
        task.terminationHandler = { task in
            print("执行 \(path)")
            onComplete(result ?? "")
        }
    }
    
}

extension PopoverVC: DestinationViewDelegate {

    func processImage(_ image: NSImage, _ path: URL?) {
        
        previewImageView.image = image
        
        if let absPath = path?.absoluteString {
            let pathString = absPath.replacingOccurrences(of: "file://", with: "")
            print("上传图片路径: \(pathString)")
            runScript(pathString) { result in
                print("执行结果: \(result)")
                let results = result.components(separatedBy: "+")
                guard results.count > 2 else {
                    print("执行结果出错！")
                    return
                }
                let value = results[results.count-3]
                if let remotePath = results.last, value == "Done" {
                    
                    let remotePathTmp = remotePath.trimmingCharacters(in: .whitespacesAndNewlines)
                    let name = results[results.count-2]
                    let md = "![\(name)](https://gitee.com/iGhibli/ihs/raw/master/Images/\(remotePathTmp))"
                    
                    DispatchQueue.main.async {
                        self.outLabel.stringValue = md
                        // 拷贝到剪切板
                        let pboard = NSPasteboard.general
                        pboard.declareTypes([.string], owner: nil)
                        pboard.setString(md, forType: .string)
                    }
                    
                }
            }
        }

    }

}
